import { reqLogin } from "@/api/user";
import { reqLogout } from "@/api/user";

const initState = JSON.parse(localStorage.getItem('user')) || {
  name: '',
  token: "",
}

export default {
  namespaced: true,
  state: initState,
  actions: {
    async login({ commit }, { phone, password }) {
      const result = await reqLogin(phone, password);
      commit("LOGIN", result);
    },
    async getLogout({ commit }) {
      await reqLogout()
      commit('GETLOGOUT')
    }
  },
  mutations: {
    LOGIN(state, user) {
      state.name = user.name;
      state.token = user.token;
      localStorage.setItem('user', JSON.stringify({
        name: user.name,
        token: user.token,
      }))
    },
    GETLOGOUT(state) {
      state.userData = {
        name: '',
        nickName: '',
        token: "",
        userId: 0
      }
      localStorage.removeItem('user')
    }
  },
};
